class tree.ui.Table extends tree.ui.Container
    constructor: (homogenous) ->
        super
        @homogenous = homogenous
        @homogenous ?= true
        @connect 'update', @update
        @htmlelem = document.createElement 'table'
        @htmlelem.className = 'tree-table-layout'
        @children = []
    
    update: (evt)  =>
        while @htmlelem.hasChildNodes()
            while @htmlelem.childNodes.length >= 1
                @htmlelem.removeChild @htmlelem.firstChild
        max_x = 0
        max_y = 0
        @rows = []
        for child in @children
            widget = child[0]
            x = child[1]
            y = child[2]
            w = child[3]
            h = child[4]
            if x > max_x
                max_x = x
            if y > max_y
                max_y = y
        for y in [0..max_y]
            tr = document.createElement 'tr'
            @rows.push tr 
            for x in [0..max_x]
                tr.appendChild document.createElement 'td'
                
        for row in @rows
            @htmlelem.appendChild row
                
        for child in @children
            widget = child[0]
            x = child[1]
            y = child[2]
            w = child[3]
            h = child[4]
            row = @rows[y]
            row.childNodes[x].style.width = w
            row.childNodes[x].setAttribute 'valign', 'top'
            row.childNodes[x].style.height = h
            row.childNodes[x].appendChild widget.show()
        null
        
        
    add: (widget, x, y, w, h) ->
        
        @children.push [widget, x, y, w, h]
        if @exposed
            @emit 'update', {}
        widget.parent = @
        
    remove: (widget) ->
        removed = false
        for child in @children
            if child[0] is widget
                @children = @children.remove child
                removed = true
        if @exposed
            @emit 'update', {}
    
    show: () ->
        max_x = 0
        max_y = 0
        @rows = []
        for child in @children
            widget = child[0]
            x = child[1]
            y = child[2]
            w = child[3]
            h = child[4]
            if x > max_x
                max_x = x
            if y > max_y
                max_y = y
        for y in [0..max_y]
            tr = document.createElement 'tr'
            @rows.push tr 
            for x in [0..max_x]
                tr.appendChild document.createElement 'td'
                
        for row in @rows
            @htmlelem.appendChild row
                
        for child in @children
            widget = child[0]
            x = child[1]
            y = child[2]
            w = child[3]
            h = child[4]
            row = @rows[y]
            row.childNodes[x].style.width = w
            row.childNodes[x].setAttribute 'valign', 'top'
            row.childNodes[x].style.height = h
            row.childNodes[x].appendChild widget.show()
        
        super
